const fs = require('fs')
const path = require('path')

function calculateCodeLines ({
  directory = '',
  writeResFilePath = '',
  fileReg = /\.(js|ts|jsx|tsx|vue|html)$/,
  blckNameList = [],
  deleteComment = true
}) {
  let totalLines = 0
  let fileList = {}
  let fileCounts = 0
  blckNameList = blckNameList.concat(['node_modules', '.lock'])
  function traverseFolder (dir) {
    const files = fs.readdirSync(dir)
    for (const file of files) {
      const filePath = path.join(dir, file)
      const stats = fs.statSync(filePath)
      if (blckNameList.some(item => filePath.includes(item))) {
        continue
      }
      if (stats.isDirectory()) {
        traverseFolder(filePath)
      } else if (
        stats.isFile() &&
        fileReg.test(file) // 只计算指定扩展名的文件
      ) {
        let code = fs.readFileSync(filePath, 'utf8')
        // 是否去除注释
        deleteComment && (code = code.replace(/\/\/(.*)/g, ''))
        deleteComment && (code = code.replace(/\/\*[\s\S]*?\*\//g, ''))
        // 统计行并且去除空行
        const lines = code.split('\n').filter(line => line.trim() !== '').length
        // 是否写入文件
        writeResFilePath && (fileList[fileCounts + 1 + '==' + filePath] = lines)
        // 累加代码行数
        totalLines += lines
        fileCounts++
      }
    }
  }

  traverseFolder(directory)
  writeResFilePath && (() => {
    fs.writeFile(writeResFilePath, JSON.stringify({ totalLines, fileCounts, fileList }, null, 2), { encoding: 'utf-8' }, (err) => {
      if (err) {
        console.log('文件写入错误', err) // zdz-log
      }
    })
  })()
  const res = { totalLines, fileCounts }
  console.log(res) // zdz-log
  return res
}


calculateCodeLines({
  // 要统计的文件夹路径
  directory: 'D:\\workSpace\\ischool-ui-microapp-child2-vue3\\src',
  // 结果是否写入文件以及文件名称 结果为JSON字符串
  writeResFilePath: 'D:\\workSpace\\ischool-ui-microapp-child2-vue3\\totalCode.json',
  // 要统计哪些格式的文件
  fileReg: /\.(js|ts|jsx|tsx|vue|html)$/,
  // 要过滤哪些文件夹或者文件不算入统计 默认会忽略 'node_modules', '.lock'
  blckNameList: [
    'slintrc'
  ],
  // 是否删除注释后统计
  deleteComment: false,
})
